<?php
namespace Auth\Controller;

use Todo\Controller\ApiController;
use Todo\Service\LoginService;
use Todo\Service\TokenService;

class LoginController extends ApiController
{

    /**
     * 登录验证
     */
    public function index()
    {
        $account = I('post.account');
        $password = I('post.password');
        if (!$account || !$password) $this->apiError('账号或密码不能为空');

        $userInfo = LoginService::getInstance()->doLogin($account, $password);
        if (!$userInfo) {
            $this->apiError('发生错误2:' . LoginService::getInstance()->getError());
        }
        $token = TokenService::getInstance()->grantToken($userInfo['id'], '');
        if (!$token) $this->apiError('发生错误3');
        $data = array(
            'nickname' => $userInfo['nickname'],
            'token' => $token
        );
        session('user', $userInfo);
        $this->apiSuccess($data, '验证成功!');

    }

    /**
     * 返回用户信息，过滤敏感数据
     * @param array $userInfo 用户详细信息
     * @param array $terminalInfo 用户所在终端的信息
     */
    protected function _returnUser($userInfo, $terminalInfo)
    {

        unset($userInfo['id'], $userInfo['password'], $userInfo['moblie'], $userInfo['email'], $userInfo['terminal_id']);
        unset($userInfo['is_del'], $userInfo['status'], $userInfo['is_super'], $userInfo['salt']);
        $userInfo['theme'] = $terminalInfo['theme'];
        $userInfo['title'] = $terminalInfo['title'];
        $userInfo['terminal'] = $terminalInfo['code'];

        $this->apiSuccess($userInfo, I('post.redirect'), '登录成功!');
    }
}